package org.thomias.swtmultithread.startstop;

import java.util.HashSet;
import java.util.Set;

public class AppMonitor implements Runnable {

	private Set<Runnable> set = null;
	private Thread t;

	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(1000);
				for (Runnable event : set) {
					event.run();
				}
			} catch (InterruptedException e) {
				return;
			}
		}
	}

	public void addTask(Runnable runnable) {
		if (set == null) {
			set = new HashSet<>();
		}
		set.add(runnable);
	}

	public void start() {
		t = new Thread(this);
		t.start();
	}

	public void stop() {
		if (t != null) {
			t.interrupt();
			t = null;
		}
		
	}
}